home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Internet Tools 1993 July / Internet Tools.iso / RockRidge / mail / pine / imap-3.0 / non-ANSI / c-client / os_hpp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-07-28  |  21.5 KB  |  813 lines

  1. /*
  2.  * Program:    Operating-system dependent routines -- HP/UX version
  3.  *
  4.  * Author:    David L. Miller
  5.  *        Computing and Telecommunications Center
  6.  *        Washington State University Tri-Cities
  7.  *        Richland, WA 99352
  8.  *        Internet: dmiller@beta.tricity.wsu.edu
  9.  *
  10.  * Date:    11 May 1989
  11.  * Last Edited:    28 July 1993
  12.  *
  13.  * Copyright 1993 by the University of Washington
  14.  *
  15.  *  Permission to use, copy, modify, and distribute this software and its
  16.  * documentation for any purpose and without fee is hereby granted, provided
  17.  * that the above copyright notice appears in all copies and that both the
  18.  * above copyright notice and this permission notice appear in supporting
  19.  * documentation, and that the name of the University of Washington not be
  20.  * used in advertising or publicity pertaining to distribution of the software
  21.  * without specific, written prior permission.  This software is made
  22.  * available "as is", and
  23.  * THE UNIVERSITY OF WASHINGTON DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
  24.  * WITH REGARD TO THIS SOFTWARE, INCLUDING WITHOUT LIMITATION ALL IMPLIED
  25.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND IN
  26.  * NO EVENT SHALL THE UNIVERSITY OF WASHINGTON BE LIABLE FOR ANY SPECIAL,
  27.  * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  28.  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, TORT
  29.  * (INCLUDING NEGLIGENCE) OR STRICT LIABILITY, ARISING OUT OF OR IN CONNECTION
  30.  * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  31.  *
  32.  */
  33.  
  34. #define isodigit(c)    (((unsigned)(c)>=060)&((unsigned)(c)<=067))
  35. #define toint(c)       ((c)-'0')
  36.  
  37.  
  38. /* TCP input buffer */
  39.  
  40. #define BUFLEN 8192
  41.  
  42.  
  43. /* TCP I/O stream (must be before osdep.h is included) */
  44.  
  45. #define TCPSTREAM struct tcp_stream
  46. TCPSTREAM {
  47.   char *host;            /* host name */
  48.   char *localhost;        /* local host name */
  49.   int tcpsi;            /* input socket */
  50.   int tcpso;            /* output socket */
  51.   int ictr;            /* input counter */
  52.   char *iptr;            /* input pointer */
  53.   char ibuf[BUFLEN];        /* input buffer */
  54. };
  55.  
  56.  
  57. #include "osdep.h"
  58. #include <sys/time.h>
  59. #include <sys/socket.h>
  60. #include <sys/utsname.h>
  61. #include <sys/file.h>
  62. #include <netinet/in.h>
  63. #include <netdb.h>
  64. #include <ctype.h>
  65. #include <errno.h>
  66. extern int errno;        /* just in case */
  67. #include <pwd.h>
  68. #include <syslog.h>
  69. #include <regex.h>
  70. #include "mail.h"
  71. #include "misc.h"
  72.  
  73. /* Write current time in RFC 822 format
  74.  * Accepts: destination string
  75.  */
  76.  
  77. char *days[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
  78.  
  79. void rfc822_date (date)
  80.     char *date;
  81. {
  82.   int zone;
  83.   char *zonename;
  84.   struct tm *t;
  85.   struct timeval tv;
  86.   struct timezone tz;
  87.   gettimeofday (&tv,&tz);    /* get time and timezone poop */
  88.   t = localtime (&tv.tv_sec);    /* convert to individual items */
  89.                 /* get timezone from TZ environment stuff */
  90.   zone = daylight ? -timezone/60 + 60 : -timezone/60;
  91.   zonename = daylight ? tzname[1] : tzname[0] ;
  92.                 /* and output it */
  93.   sprintf (date,"%s, %d %s %d %02d:%02d:%02d %+03d%02d (%s)",
  94.        days[t->tm_wday],t->tm_mday,months[t->tm_mon],t->tm_year+1900,
  95.        t->tm_hour,t->tm_min,t->tm_sec,zone/60,abs (zone) % 60,zonename);
  96. }
  97.  
  98. /* Get a block of free storage
  99.  * Accepts: size of desired block
  100.  * Returns: free storage block
  101.  */
  102.  
  103. void *fs_get (size)
  104.     size_t size;
  105. {
  106.   void *block = malloc (size);
  107.   if (!block) fatal ("Out of free storage");
  108.   return (block);
  109. }
  110.  
  111.  
  112. /* Resize a block of free storage
  113.  * Accepts: ** pointer to current block
  114.  *        new size
  115.  */
  116.  
  117. void fs_resize (block,size)
  118.     void **block;
  119.     size_t size;
  120. {
  121.   if (!(*block = realloc (*block,size))) fatal ("Can't resize free storage");
  122. }
  123.  
  124.  
  125. /* Return a block of free storage
  126.  * Accepts: ** pointer to free storage block
  127.  */
  128.  
  129. void fs_give (block)
  130.     void **block;
  131. {
  132.   free (*block);
  133.   *block = NIL;
  134. }
  135.  
  136.  
  137. /* Report a fatal error
  138.  * Accepts: string to output
  139.  */
  140.  
  141. void fatal (string)
  142.     char *string;
  143. {
  144.   mm_fatal (string);        /* output the string */
  145.   syslog (LOG_ALERT,"IMAP C-Client crash: %s",string);
  146.   abort ();            /* die horribly */
  147. }
  148.  
  149. /* Copy string with CRLF newlines
  150.  * Accepts: destination string
  151.  *        pointer to size of destination string
  152.  *        source string
  153.  *        length of source string
  154.  */
  155.  
  156. char *strcrlfcpy (dst,dstl,src,srcl)
  157.     char **dst;
  158.     unsigned long *dstl;
  159.     char *src;
  160.     unsigned long srcl;
  161. {
  162.   long i,j;
  163.   char *d = src;
  164.                 /* count number of LF's in source string(s) */
  165.   for (i = srcl,j = 0; j < srcl; j++) if (*d++ == '\012') i++;
  166.   if (i > *dstl) {        /* resize if not enough space */
  167.     fs_give ((void **) dst);    /* fs_resize does an unnecessary copy */
  168.     *dst = (char *) fs_get ((*dstl = i) + 1);
  169.   }
  170.   d = *dst;            /* destination string */
  171.                 /* copy strings, inserting CR's before LF's */
  172.   while (srcl--) switch (*src) {
  173.   case '\015':            /* unlikely carriage return */
  174.     *d++ = *src++;        /* copy it and any succeeding linefeed */
  175.     if (srcl && *src == '\012') {
  176.       *d++ = *src++;
  177.       srcl--;
  178.     }
  179.     break;
  180.   case '\012':            /* line feed? */
  181.     *d++ ='\015';        /* yes, prepend a CR, drop into default case */
  182.   default:            /* ordinary chararacter */
  183.     *d++ = *src++;        /* just copy character */
  184.     break;
  185.   }
  186.   *d = '\0';            /* tie off destination */
  187.   return *dst;            /* return destination */
  188. }
  189.  
  190.  
  191. /* Length of string after strcrlfcpy applied
  192.  * Accepts: source string
  193.  *        length of source string
  194.  */
  195.  
  196. unsigned long strcrlflen (s)
  197.     STRING *s;
  198. {
  199.   unsigned long pos = GETPOS (s);
  200.   unsigned long i = SIZE (s);
  201.   unsigned long j = i;
  202.   while (j--) switch (SNX (s)) {/* search for newlines */
  203.   case '\015':            /* unlikely carriage return */
  204.     if (j && (CHR (s) == '\012')) {
  205.       SNX (s);            /* eat the line feed */
  206.       j--;
  207.     }
  208.     break;
  209.   case '\012':            /* line feed? */
  210.     i++;
  211.   default:            /* ordinary chararacter */
  212.     break;
  213.   }
  214.   SETPOS (s,pos);        /* restore old position */
  215.   return i;
  216. }
  217.  
  218. /* Server log in
  219.  * Accepts: user name string
  220.  *        password string
  221.  *        optional place to return home directory
  222.  * Returns: T if password validated, NIL otherwise
  223.  */
  224.  
  225. long server_login (user,pass,home,argc,argv)
  226.     char *user;
  227.     char *pass;
  228.     char **home;
  229.     int argc;
  230.     char *argv[];
  231. {
  232.   struct passwd *pw = getpwnam (lcase (user));
  233.                 /* no entry for this user or root */
  234.   if (!(pw && pw->pw_uid)) return NIL;
  235.                 /* validate password */
  236.   if (strcmp (pw->pw_passwd,(char *) crypt (pass,pw->pw_passwd))) return NIL;
  237.   setgid (pw->pw_gid);        /* all OK, login in as that user */
  238.   initgroups (user,pw->pw_gid);    /* initialize groups */
  239.   setuid (pw->pw_uid);
  240.                 /* note home directory */
  241.   if (home) *home = cpystr (pw->pw_dir);
  242.   return T;
  243. }
  244.  
  245. /* Return my user name
  246.  * Returns: my user name
  247.  */
  248.  
  249. char *cuname = NIL;
  250.  
  251. char *myusername ()
  252. {
  253.   return cuname ? cuname : (cuname = cpystr (getpwuid (geteuid ())->pw_name));
  254. }
  255.  
  256.  
  257. /* Return my home directory name
  258.  * Returns: my home directory name
  259.  */
  260.  
  261. char *hdname = NIL;
  262.  
  263. char *myhomedir ()
  264. {
  265.   return hdname ? hdname : (hdname = cpystr (getpwuid (geteuid ())->pw_dir));
  266. }
  267.  
  268.  
  269. /* Build status lock file name
  270.  * Accepts: scratch buffer
  271.  *        file name
  272.  * Returns: name of file to lock
  273.  */
  274.  
  275. char *lockname (tmp,fname)
  276.     char *tmp;
  277.     char *fname;
  278. {
  279.   int i;
  280.   sprintf (tmp,"/tmp/.%s",fname);
  281.   for (i = 6; i < strlen (tmp); ++i) if (tmp[i] == '/') tmp[i] = '\\';
  282.   return tmp;            /* note name for later */
  283. }
  284.  
  285. /* TCP/IP open
  286.  * Accepts: host name
  287.  *        contact port number
  288.  * Returns: TCP/IP stream if success else NIL
  289.  */
  290.  
  291. TCPSTREAM *tcp_open (host,port)
  292.     char *host;
  293.     long port;
  294. {
  295.   TCPSTREAM *stream = NIL;
  296.   int sock;
  297.   char *s;
  298.   struct sockaddr_in sin;
  299.   struct hostent *host_name;
  300.   char hostname[MAILTMPLEN];
  301.   char tmp[MAILTMPLEN];
  302.   /* The domain literal form is used (rather than simply the dotted decimal
  303.      as with other Unix programs) because it has to be a valid "host name"
  304.      in mailsystem terminology. */
  305.                 /* look like domain literal? */
  306.   if (host[0] == '[' && host[(strlen (host))-1] == ']') {
  307.     strcpy (hostname,host+1);    /* yes, copy number part */
  308.     hostname[(strlen (hostname))-1] = '\0';
  309.     if ((sin.sin_addr.s_addr = inet_addr (hostname)) != -1) {
  310.       sin.sin_family = AF_INET;    /* family is always Internet */
  311.       strcpy (hostname,host);    /* hostname is user's argument */
  312.     }
  313.     else {
  314.       sprintf (tmp,"Bad format domain-literal: %.80s",host);
  315.       mm_log (tmp,ERROR);
  316.       return NIL;
  317.     }
  318.   }
  319.  
  320.   else {            /* lookup host name, note that brain-dead Unix
  321.                    requires lowercase! */
  322.     strcpy (hostname,host);    /* in case host is in write-protected memory */
  323.     if ((host_name = gethostbyname (lcase (hostname)))) {
  324.                 /* copy address type */
  325.       sin.sin_family = host_name->h_addrtype;
  326.                 /* copy host name */
  327.       strcpy (hostname,host_name->h_name);
  328.                 /* copy host addresses */
  329.       memcpy (&sin.sin_addr,host_name->h_addr,host_name->h_length);
  330.     }
  331.     else {
  332.       sprintf (tmp,"No such host as %.80s",host);
  333.       mm_log (tmp,ERROR);
  334.       return NIL;
  335.     }
  336.   }
  337.  
  338.                 /* copy port number in network format */
  339.   if (!(sin.sin_port = htons (port))) fatal ("Bad port argument to tcp_open");
  340.                 /* get a TCP stream */
  341.   if ((sock = socket (sin.sin_family,SOCK_STREAM,0)) < 0) {
  342.     sprintf (tmp,"Unable to create TCP socket: %s",strerror (errno));
  343.     mm_log (tmp,ERROR);
  344.     return NIL;
  345.   }
  346.                 /* open connection */
  347.   if (connect (sock,(struct sockaddr *)&sin,sizeof (sin)) < 0) {
  348.     sprintf (tmp,"Can't connect to %.80s,%d: %s",hostname,port,
  349.          strerror (errno));
  350.     mm_log (tmp,ERROR);
  351.     return NIL;
  352.   }
  353.                 /* create TCP/IP stream */
  354.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  355.                 /* copy official host name */
  356.   stream->host = cpystr (hostname);
  357.                 /* get local name */
  358.   gethostname (tmp,MAILTMPLEN-1);
  359.   stream->localhost = cpystr ((host_name = gethostbyname (tmp)) ?
  360.                   host_name->h_name : tmp);
  361.                 /* init sockets */
  362.   stream->tcpsi = stream->tcpso = sock;
  363.   stream->ictr = 0;        /* init input counter */
  364.   return stream;        /* return success */
  365. }
  366.  
  367. /* TCP/IP authenticated open
  368.  * Accepts: host name
  369.  *        service name
  370.  * Returns: TCP/IP stream if success else NIL
  371.  */
  372.  
  373. TCPSTREAM *tcp_aopen (host,service)
  374.     char *host;
  375.     char *service;
  376. {
  377.   TCPSTREAM *stream = NIL;
  378.   struct hostent *host_name;
  379.   char hostname[MAILTMPLEN];
  380.   int i;
  381.   int pipei[2],pipeo[2];
  382.   /* The domain literal form is used (rather than simply the dotted decimal
  383.      as with other Unix programs) because it has to be a valid "host name"
  384.      in mailsystem terminology. */
  385.                 /* look like domain literal? */
  386.   if (host[0] == '[' && host[i = (strlen (host))-1] == ']') {
  387.     strcpy (hostname,host+1);    /* yes, copy without brackets */
  388.     hostname[i-1] = '\0';
  389.   }
  390.                 /* note that Unix requires lowercase! */
  391.   else if (host_name = gethostbyname (lcase (strcpy (hostname,host))))
  392.     strcpy (hostname,host_name->h_name);
  393.                 /* make command pipes */
  394.   if (pipe (pipei) < 0) return NIL;
  395.   if (pipe (pipeo) < 0) {
  396.     close (pipei[0]); close (pipei[1]);
  397.     return NIL;
  398.   }
  399.   if ((i = fork ()) < 0) {    /* make inferior process */
  400.     close (pipei[0]); close (pipei[1]);
  401.     close (pipeo[0]); close (pipeo[1]);
  402.     return NIL;
  403.   }
  404.   if (i) {            /* parent? */
  405.     close (pipei[1]);        /* close child's side of the pipes */
  406.     close (pipeo[0]);
  407.   }
  408.   else {            /* child */
  409.     dup2 (pipei[1],1);        /* parent's input is my output */
  410.     dup2 (pipei[1],2);        /* parent's input is my error output too */
  411.     close (pipei[0]); close (pipei[1]);
  412.     dup2 (pipeo[0],0);        /* parent's output is my input */
  413.     close (pipeo[0]); close (pipeo[1]);
  414.                 /* now run it */
  415.     execl ("/usr/bin/remsh","remsh",hostname,"exec",service,0);
  416.     _exit (1);            /* spazzed */
  417.   }
  418.  
  419.                 /* create TCP/IP stream */
  420.   stream = (TCPSTREAM *) fs_get (sizeof (TCPSTREAM));
  421.                 /* copy official host name */
  422.   stream->host = cpystr (hostname);
  423.                 /* get local name */
  424.   gethostname (hostname,MAILTMPLEN-1);
  425.   stream->localhost = cpystr ((host_name = gethostbyname (hostname)) ?
  426.                   host_name->h_name : hostname);
  427.   stream->tcpsi = pipei[0];    /* init sockets */
  428.   stream->tcpso = pipeo[1];
  429.   stream->ictr = 0;        /* init input counter */
  430.   return stream;        /* return success */
  431. }
  432.  
  433. /* TCP/IP receive line
  434.  * Accepts: TCP/IP stream
  435.  * Returns: text line string or NIL if failure
  436.  */
  437.  
  438. char *tcp_getline (stream)
  439.     TCPSTREAM *stream;
  440. {
  441.   int n,m;
  442.   char *st,*ret,*stp;
  443.   char c = '\0';
  444.   char d;
  445.                 /* make sure have data */
  446.   if (!tcp_getdata (stream)) return NIL;
  447.   st = stream->iptr;        /* save start of string */
  448.   n = 0;            /* init string count */
  449.   while (stream->ictr--) {    /* look for end of line */
  450.     d = *stream->iptr++;    /* slurp another character */
  451.     if ((c == '\015') && (d == '\012')) {
  452.       ret = (char *) fs_get (n--);
  453.       memcpy (ret,st,n);    /* copy into a free storage string */
  454.       ret[n] = '\0';        /* tie off string with null */
  455.       return ret;
  456.     }
  457.     n++;            /* count another character searched */
  458.     c = d;            /* remember previous character */
  459.   }
  460.                 /* copy partial string from buffer */
  461.   memcpy ((ret = stp = (char *) fs_get (n)),st,n);
  462.                 /* get more data from the net */
  463.   if (!tcp_getdata (stream)) return NIL;
  464.                 /* special case of newline broken by buffer */
  465.   if ((c == '\015') && (*stream->iptr == '\012')) {
  466.     stream->iptr++;        /* eat the line feed */
  467.     stream->ictr--;
  468.     ret[n - 1] = '\0';        /* tie off string with null */
  469.   }
  470.                 /* else recurse to get remainder */
  471.   else if (st = tcp_getline (stream)) {
  472.     ret = (char *) fs_get (n + 1 + (m = strlen (st)));
  473.     memcpy (ret,stp,n);        /* copy first part */
  474.     memcpy (ret + n,st,m);    /* and second part */
  475.     fs_give ((void **) &stp);    /* flush first part */
  476.     fs_give ((void **) &st);    /* flush second part */
  477.     ret[n + m] = '\0';        /* tie off string with null */
  478.   }
  479.   return ret;
  480. }
  481.  
  482. /* TCP/IP receive buffer
  483.  * Accepts: TCP/IP stream
  484.  *        size in bytes
  485.  *        buffer to read into
  486.  * Returns: T if success, NIL otherwise
  487.  */
  488.  
  489. long tcp_getbuffer (stream,size,buffer)
  490.     TCPSTREAM *stream;
  491.     unsigned long size;
  492.     char *buffer;
  493. {
  494.   unsigned long n;
  495.   char *bufptr = buffer;
  496.   while (size > 0) {        /* until request satisfied */
  497.     if (!tcp_getdata (stream)) return NIL;
  498.     n = min (size,stream->ictr);/* number of bytes to transfer */
  499.                 /* do the copy */
  500.     memcpy (bufptr,stream->iptr,n);
  501.     bufptr += n;        /* update pointer */
  502.     stream->iptr +=n;
  503.     size -= n;            /* update # of bytes to do */
  504.     stream->ictr -=n;
  505.   }
  506.   bufptr[0] = '\0';        /* tie off string */
  507.   return T;
  508. }
  509.  
  510.  
  511. /* TCP/IP receive data
  512.  * Accepts: TCP/IP stream
  513.  * Returns: T if success, NIL otherwise
  514.  */
  515.  
  516. long tcp_getdata (stream)
  517.     TCPSTREAM *stream;
  518. {
  519.   fd_set fds;
  520.   FD_ZERO (&fds);        /* initialize selection vector */
  521.   if (stream->tcpsi < 0) return NIL;
  522.   while (stream->ictr < 1) {    /* if nothing in the buffer */
  523.     FD_SET (stream->tcpsi,&fds);/* set bit in selection vector */
  524.                 /* block and read */
  525.     if ((select (stream->tcpsi+1,&fds,0,0,0) < 0) ||
  526.     ((stream->ictr = read (stream->tcpsi,stream->ibuf,BUFLEN)) < 1)) {
  527.       close (stream->tcpsi);    /* nuke the socket */
  528.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  529.       stream->tcpsi = stream->tcpso = -1;
  530.       return NIL;
  531.     }
  532.     stream->iptr = stream->ibuf;/* point at TCP buffer */
  533.   }
  534.   return T;
  535. }
  536.  
  537. /* TCP/IP send string as record
  538.  * Accepts: TCP/IP stream
  539.  *        string pointer
  540.  * Returns: T if success else NIL
  541.  */
  542.  
  543. long tcp_soutr (stream,string)
  544.     TCPSTREAM *stream;
  545.     char *string;
  546. {
  547.   return tcp_sout (stream,string,(unsigned long) strlen (string));
  548. }
  549.  
  550.  
  551. /* TCP/IP send string
  552.  * Accepts: TCP/IP stream
  553.  *        string pointer
  554.  *        byte count
  555.  * Returns: T if success else NIL
  556.  */
  557.  
  558. long tcp_sout (stream,string,size)
  559.     TCPSTREAM *stream;
  560.     char *string;
  561.     unsigned long size;
  562. {
  563.   int i;
  564.   fd_set fds;
  565.   FD_ZERO (&fds);        /* initialize selection vector */
  566.   if (stream->tcpso < 0) return NIL;
  567.   while (size > 0) {        /* until request satisfied */
  568.     FD_SET (stream->tcpso,&fds);/* set bit in selection vector */
  569.     if ((select (stream->tcpso+1,0,&fds,0,0) < 0) ||
  570.     ((i = write (stream->tcpso,string,size)) < 0)) {
  571.       puts (strerror (errno));
  572.       close (stream->tcpsi);    /* nuke the socket */
  573.       if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  574.       stream->tcpsi = stream->tcpso = -1;
  575.       return NIL;
  576.     }
  577.     size -= i;            /* count this size */
  578.     string += i;
  579.   }
  580.   return T;            /* all done */
  581. }
  582.  
  583. /* TCP/IP close
  584.  * Accepts: TCP/IP stream
  585.  */
  586.  
  587. void tcp_close (stream)
  588.     TCPSTREAM *stream;
  589. {
  590.  
  591.   if (stream->tcpsi >= 0) {    /* no-op if no socket */
  592.     close (stream->tcpsi);    /* nuke the socket */
  593.     if (stream->tcpsi != stream->tcpso) close (stream->tcpso);
  594.     stream->tcpsi = stream->tcpso = -1;
  595.   }
  596.                 /* flush host names */
  597.   fs_give ((void **) &stream->host);
  598.   fs_give ((void **) &stream->localhost);
  599.   fs_give ((void **) &stream);    /* flush the stream */
  600. }
  601.  
  602.  
  603. /* TCP/IP get host name
  604.  * Accepts: TCP/IP stream
  605.  * Returns: host name for this stream
  606.  */
  607.  
  608. char *tcp_host (stream)
  609.     TCPSTREAM *stream;
  610. {
  611.   return stream->host;        /* return host name */
  612. }
  613.  
  614.  
  615. /* TCP/IP get local host name
  616.  * Accepts: TCP/IP stream
  617.  * Returns: local host name
  618.  */
  619.  
  620. char *tcp_localhost (stream)
  621.     TCPSTREAM *stream;
  622. {
  623.   return stream->localhost;    /* return local host name */
  624. }
  625.  
  626.  
  627.  
  628. /* Return pointer to first occurance in string of a substring
  629.  * Accepts: source pointer
  630.  *        substring pointer
  631.  * Returns: pointer to substring in source or NIL if not found
  632.  */
  633.  
  634. char *strstr (cs,ct)
  635.      char *cs;
  636.      char *ct;
  637. {
  638.   char *s;
  639.   char *t;
  640.   while (cs = strchr (cs,*ct)) {/* for each occurance of the first character */
  641.                 /* see if remainder of string matches */
  642.     for (s = cs + 1, t = ct + 1; *t && *s == *t; s++, t++);
  643.     if (!*t) return cs;        /* if ran out of substring then have match */
  644.     cs++;            /* try from next character */
  645.   }
  646.   return NIL;            /* not found */
  647. }
  648.  
  649. /* Return implementation-defined string corresponding to error
  650.  * Accepts: error number
  651.  * Returns: string for that error
  652.  */
  653.  
  654. char *strerror (n)
  655.      int n;
  656. {
  657.   extern char *sys_errlist[];
  658.   extern int sys_nerr;
  659.  
  660.   return (n >= 0 && n < sys_nerr) ? sys_errlist[n] : NIL;
  661. }
  662.  
  663.  
  664. /*
  665.  * Turn a string long into the real thing
  666.  * Accepts: source string
  667.  *        pointer to place to return end pointer
  668.  *        base
  669.  * Returns: parsed long integer, end pointer is updated
  670.  */
  671.  
  672. long strtol (s,endp,base)
  673.      char *s;
  674.      char **endp;
  675.      int base;
  676. {
  677.   long value = 0;        /* the accumulated value */
  678.   int negative = 0;        /* this a negative number? */
  679.   int ok;            /* true while valid chars for number */
  680.   char c;
  681.                 /* insist upon valid base */
  682.   if (base && (base < 2 || base > 36)) return NIL;
  683.   while (isspace (*s)) s++;    /* skip leading whitespace */
  684.   if (!base) {            /* if base = 0, */
  685.     if (*s == '-') {        /* integer constants are allowed a */
  686.       negative = 1;        /* leading unary minus, but not */
  687.       s++;            /* unary plus. */
  688.     }
  689.     else negative = 0;
  690.     if (*s == '0') {        /* if it starts with 0, its either */
  691.                 /* 0X, which marks a hex constant, */
  692.       if (toupper (*++s) == 'X') {
  693.     s++;            /* skip the X */
  694.            base = 16;        /* base is hex 16 */
  695.       }
  696.       else base = 8;        /* leading 0 means octal number */
  697.     }
  698.     else base = 10;        /* otherwise, decimal. */
  699.     do {
  700.       switch (base) {        /* char has to be valid for base */
  701.       case 8:            /* this digit ok? */
  702.     ok = isodigit(*s);
  703.     break;
  704.       case 10:
  705.     ok = isdigit(*s);
  706.     break;
  707.       case 16:
  708.     ok = isxdigit(*s);
  709.     break;
  710.       default:            /* it's good form you know */
  711.     return NIL;
  712.       }
  713.                 /* if valid char, accumulate */
  714.       if (ok) value = value * base + toint(*s++);
  715.     } while (ok);
  716.     if (toupper(*s) == 'L') s++;/* ignore 'l' or 'L' marker */
  717.     if (endp) *endp = s;    /* set user pointer to after num */
  718.     return (negative) ? -value : value;
  719.   }
  720.  
  721.   switch (*s) {            /* check for leading sign char */
  722.   case '-':
  723.     negative = 1;        /* yes, negative #.  fall into '+' */
  724.   case '+':
  725.     s++;            /* skip the sign character */
  726.   }
  727.                 /* allow hex prefix "0x" */
  728.   if (base == 16 && *s == '0' && toupper (*(s + 1)) == 'X') s += 2;
  729.   do {
  730.                 /* convert to numeric form if digit*/
  731.     if (isdigit (*s)) c = toint (*s);
  732.                 /* alphabetic conversion */
  733.     else if (isalpha (*s)) c = *s - (isupper (*s) ? 'A' : 'a') + 10;
  734.     else break;            /* else no way it's valid */
  735.     if (c >= base) break;    /* digit out of range for base? */
  736.     value = value * base + c;    /* accumulate the digit */
  737.   } while (*++s);        /* loop until non-numeric character */
  738.   if (endp) *endp = s;        /* save users endp to after number */
  739.                 /* negate number if needed */
  740.   return (negative) ? -value : value;
  741. }
  742.  
  743. /* Emulator for BSD gethostid() call
  744.  * Returns: a unique identifier for the system.  
  745.  * Even though HP/UX has an undocumented gethostid() system call,
  746.  * it does not work (at least for non-priviliged users).  
  747.  */
  748.  
  749. long gethostid ()
  750. {
  751.   struct utsname udata;
  752.   if (uname (&udata)) return 0 ;
  753.   return atol (udata.idnumber);
  754. }
  755.  
  756.  
  757. /* Emulator for BSD random() call
  758.  * Returns: a random number between 0 and 2^31
  759.  */
  760.  
  761. long random ()
  762. {
  763.   return lrand48 ();
  764. }
  765.  
  766. /* Emulator for BSD flock() call
  767.  * Accepts: file descriptor
  768.  *        operation bitmask
  769.  * Returns: 0 if successful, -1 if failure
  770.  * Note: this emulator does not handle shared locks
  771.  */
  772.  
  773. int flock (fd, operation)
  774.     int fd;
  775.     int operation;
  776. {
  777.   int func;
  778.   off_t offset = lseek (fd,0,L_INCR);
  779.   switch (operation & ~LOCK_NB){/* translate to lockf() operation */
  780.   case LOCK_EX:            /* exclusive */
  781.   case LOCK_SH:            /* shared */
  782.     func = (operation & LOCK_NB) ? F_TLOCK : F_LOCK;
  783.     break;
  784.   case LOCK_UN:            /* unlock */
  785.     func = F_ULOCK;
  786.     break;
  787.   default:            /* default */
  788.     errno = EINVAL;
  789.     return -1;
  790.   }
  791.   lseek (fd,0,L_SET);        /* position to start of the file */
  792.   func = lockf (fd,func,0);    /* do the lockf() */
  793.   lseek (fd,offset,L_SET);    /* restore prior position */
  794.   return func;
  795. }
  796.  
  797.  
  798. /* Emulator for BSD utimes() call
  799.  * Accepts: file name
  800.  *        timeval vector for access and updated time
  801.  * Returns: 0 if successful, -1 if failure
  802.  */
  803.  
  804. int utimes (file,tvp)
  805.     char *file;
  806.     struct timeval tvp[2];
  807. {
  808.   struct utimbuf tb;
  809.   tb.actime = tvp[0].tv_sec;    /* accessed time */
  810.   tb.modtime = tvp[1].tv_sec;    /* updated time */
  811.   return utime (file,&tb);
  812. }
  813.